package com.example.notificationtest

import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import android.media.ExifInterface
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import android.widget.Button
import android.widget.ImageView
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.NotificationCompat
import androidx.core.content.FileProvider
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import java.io.File

class MainActivity : AppCompatActivity() {


    private val channelId = "channelId"
    private val channelName = "channelName"
    private val channelName1 = "channelName1"
    private val channelId1 = "channelId1"

    lateinit var imageUri:Uri
    lateinit var launcher: ActivityResultLauncher<Intent>
    lateinit var launcher1: ActivityResultLauncher<Intent>
    lateinit var outputFile:File

    @RequiresApi(Build.VERSION_CODES.O)
    override fun onCreate(savedInstanceState: Bundle?) {

        // 目录测试
        val internalStorageDir = Environment.getDataDirectory() // /data
        val externalStorageDir = Environment.getExternalStorageDirectory() // /Storage/emulated/0
        val externalStoragePublicDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) // /Storage/emulated/0/Pictures


        val TAG = javaClass.simpleName
        Log.d(TAG, "onCreate: $internalStorageDir")
        Log.d(TAG, "onCreate: $externalStorageDir")
        Log.d(TAG, "onCreate: $externalStoragePublicDirectory")

        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        // button
        val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        val intent = Intent(this, MainActivity::class.java)

        val channel = NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_DEFAULT)
        manager.createNotificationChannel(channel)

        val button = findViewById<Button>(R.id.button)
        button.setOnClickListener{

            val pi = PendingIntent.getActivity(this, 0, intent,
                PendingIntent.FLAG_ONE_SHOT or PendingIntent.FLAG_IMMUTABLE)
            val notification = NotificationCompat.Builder(this, channelId)
                .setContentTitle("Title")
                .setContentText("Text")
                .setSmallIcon( R.drawable.ic_launcher_foreground)
                .setLargeIcon( BitmapFactory.decodeResource(resources, R.drawable.ic_launcher_background))
                .setContentIntent(pi)
                .setAutoCancel(true)
                .setStyle(NotificationCompat.BigTextStyle().bigText("ssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss"))
                .build()

            manager.notify(1,notification)
        }

        // button2
        val channel1 = NotificationChannel(channelId1, channelName1, NotificationManager.IMPORTANCE_HIGH)
        manager.createNotificationChannel(channel1)
        val button2 = findViewById<Button>(R.id.button2)
        button2.setOnClickListener{

            val pi = PendingIntent.getActivity(this, 0, intent,
                PendingIntent.FLAG_ONE_SHOT or PendingIntent.FLAG_IMMUTABLE)
            val notification1 = NotificationCompat.Builder(this, channelId1)
                .setContentText("TextHigh")
                .setContentTitle("TitleHigh")
                .setSmallIcon(R.drawable.ic_launcher_background)
                .setLargeIcon(BitmapFactory.decodeResource(resources, R.drawable.ic_launcher_foreground))
                .setStyle(NotificationCompat.BigPictureStyle().bigPicture(BitmapFactory.decodeResource(resources, R.drawable.big_image)))
                .setAutoCancel(true)
                .setContentIntent(pi)
                .build()

            manager.notify(2, notification1)
        }

        // take photo
        launcher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()){
            res:ActivityResult->
            if(res.resultCode == RESULT_OK){
                val bitmap = BitmapFactory.decodeStream(contentResolver.openInputStream(imageUri))
                val imageView = findViewById<ImageView>(R.id.imageView)
                imageView.setImageBitmap(retotaIfNeed(bitmap))
            }
        }
        outputFile = File(externalCacheDir,"output.jpg")
        if(outputFile.exists())
            outputFile.delete()
        outputFile.createNewFile()

        // Build.VERSION_CODES.N : 24 之后 file:// （Uri）没有权限访问外部存储的私有目录, 必须使用 content:// 访问，（FileProvider）
        imageUri = FileProvider.getUriForFile(this, "$packageName.provider", outputFile)
//        imageUri = Uri.fromFile(outputFile) //

        val takePhoneButton = findViewById<Button>(R.id.button3)
        takePhoneButton.setOnClickListener{
            takePhoto()
        }

        // from album
        launcher1 = registerForActivityResult(ActivityResultContracts.StartActivityForResult()){
            res:ActivityResult->
            if(res.resultCode == RESULT_OK){
                val bitmap = getBitmapFromUri(res.data?.data!!)
                val imageView = findViewById<ImageView>(R.id.imageView)
                imageView.setImageBitmap(retotaIfNeed(bitmap!!))
            }
        }

        val fromAlbumButton = findViewById<Button>(R.id.button4)
        fromAlbumButton.setOnClickListener{
            fromAlbum(TAG)
        }

    }

    private fun fromAlbum(TAG: String?) {
        try {
            val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
            intent.addCategory(Intent.CATEGORY_OPENABLE)
            intent.type = "image/*"
            launcher1.launch(intent)
        } catch (e: Exception) {
            Log.e(TAG, "onCreate: ${e.message}")
        }
    }

    private fun getBitmapFromUri(uri: Uri) = contentResolver.openFileDescriptor(uri, "r")?.use {
            BitmapFactory.decodeFileDescriptor(it.fileDescriptor)
    }


    private fun takePhoto(){
        try {
            val intent1 = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
            intent1.putExtra(MediaStore.EXTRA_OUTPUT, imageUri)
            launcher.launch(intent1)
        } catch (e: Exception) {
            Log.e(javaClass.simpleName, "takePhoto: ${e.message}", )
        }
    }

    private fun retotaIfNeed(bitmap:Bitmap):Bitmap
    {
        val exif = ExifInterface(outputFile.path)
        val oritation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL)
        return when (oritation) {
            ExifInterface.ORIENTATION_ROTATE_90->rotateBitmap(bitmap, 90)
            ExifInterface.ORIENTATION_ROTATE_90->rotateBitmap(bitmap, 180)
            ExifInterface.ORIENTATION_ROTATE_90->rotateBitmap(bitmap, 270)
            else -> bitmap
        }
    }

    private fun rotateBitmap(bitmap:Bitmap, degree: Int):Bitmap
    {
        val matrix = Matrix()
        matrix.postRotate(degree.toFloat())
        val rotatedBitmap = Bitmap.createBitmap(bitmap, 0,0, bitmap.width, bitmap.height, matrix, true)
        bitmap.recycle()
        return rotatedBitmap
    }
}